package com.ikas.ai.server.security;

import com.auth0.jwt.JWT;
import com.auth0.jwt.JWTVerifier;
import com.auth0.jwt.algorithms.Algorithm;
import com.auth0.jwt.exceptions.JWTDecodeException;
import com.auth0.jwt.interfaces.DecodedJWT;
import com.ikas.ai.consts.Consts;
import com.ikas.ai.server.error.BusinessException;
import com.ikas.ai.utils.EncryptUtil;
import com.ikas.ai.utils.ServletUtils;
import org.apache.commons.lang.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Component;

import javax.servlet.ServletRequest;
import javax.servlet.http.Cookie;
import javax.servlet.http.HttpServletRequest;
import java.util.Arrays;
import java.util.Date;
import java.util.List;
import java.util.stream.Collectors;

/**
 * @author deng.baohui
 * JAVA-JWT工具类
 */
@Component
public class JwtUtil {

    /**
     * logger
     */
    private static final Logger logger = LoggerFactory.getLogger(JwtUtil.class);

    public static String cookieOn;

    @Value("${ikas.cookie}")
    public void setCookieOn(String cookieOn) {
        JwtUtil.cookieOn = cookieOn;
    }

    /**
     * 过期时间改为从配置文件获取
     */
    private static String accessTokenExpireTime;

    /**
     * JWT认证加密私钥(Base64加密)
     */
    private static String encryptJWTKey;

    @Value("${accessTokenExpireTime}")
    public void setAccessTokenExpireTime(String accessTokenExpireTime) {
        JwtUtil.accessTokenExpireTime = accessTokenExpireTime;
    }

    @Value("${encryptJWTKey}")
    public void setEncryptJWTKey(String encryptJWTKey) {
        JwtUtil.encryptJWTKey = encryptJWTKey;
    }



    /**
     * 校验token是否正确
     *
     * @param token Token
     * @return boolean 是否正确
     */
    public static boolean verify(String token) {
        try {
            // 帐号加JWT私钥解密
            String secret = getClaim(token, Consts.ACCOUNT) + EncryptUtil.decodeStr(encryptJWTKey);
            Algorithm algorithm = Algorithm.HMAC256(secret);
            JWTVerifier verifier = JWT.require(algorithm).build();
            verifier.verify(token);
            return true;
        } catch (Exception e) {
            logger.error("JWTToken verify error:{}", e.getMessage());
            return false;
        }
    }

    /**
     * 获得Token中的信息无需secret解密也能获得
     *
     * @param token
     * @param claim
     * @return java.lang.String
     */
    public static String getClaim(String token, String claim) {
        try {
            DecodedJWT jwt = JWT.decode(token);
            // 只能输出String类型，如果是其他类型返回null
            return jwt.getClaim(claim).asString();
        } catch (JWTDecodeException e) {
            logger.error("decode Token error:{}", e.getMessage());
            throw new BusinessException("解密token出现异常," + e.getMessage());
        }
    }

    /**
     * 生成签名
     *
     * @param username 帐号
     * @return java.lang.String 返回加密的Token
     */
    public static String generateJwt(String username, String currentTimeMillis) {
        // 此处过期时间是以毫秒为单位，所以乘以1000
        Date date = new Date(System.currentTimeMillis() + Long.parseLong(accessTokenExpireTime) * 1000);
        return generateJwt(username, currentTimeMillis, date);
    }

    /**
     * 生成签名
     *
     * @param username 帐号
     * @return java.lang.String 返回加密的Token
     */
    private static String generateJwt(String username, String currentTimeMillis, Date date) {
        try {
            // 帐号加JWT私钥加密
            String secret = username + EncryptUtil.decodeStr(encryptJWTKey);
            Algorithm algorithm = Algorithm.HMAC256(secret);
            // 附带account帐号信息
            return JWT.create()
                    .withClaim(Consts.ACCOUNT, username)
                    .withClaim("currentTimeMillis", currentTimeMillis)
                    .withExpiresAt(date)
                    .sign(algorithm);
        } catch (Exception e) {
            logger.error("JWTToken sign error:{}", e.getMessage());
            throw new BusinessException("JWTToken加密出现异常:" + e.getMessage());
        }
    }

    //根据token字符串得到用户名称
    public static String getAccount(String token) {
        if (StringUtils.isEmpty(token)) {
            throw new BusinessException("认证失败");
        }
        return JWT.decode(token).getClaim(Consts.ACCOUNT).asString();
    }

    /**
     * 获取token
     *
     * @param request
     * @return
     */
    public static String getAuthzHeader(ServletRequest request) {
        HttpServletRequest httpRequest = ServletUtils.getRequest();
        String authorization = httpRequest.getHeader(Consts.TOKEN);
        if (StringUtils.isBlank(authorization)) {
            authorization = request.getParameter(Consts.TOKEN);
        }
        if (StringUtils.isBlank(authorization) && Consts.ON.equals(cookieOn)) {
            //方便Postman测试，避免每次都需要拷贝token，正式版可以去掉从cookie中取token
            Cookie[] cookies = httpRequest.getCookies();
            if (cookies != null) {
                List<Cookie> list = Arrays.stream(cookies).filter(item -> item != null && item.getName().equalsIgnoreCase(Consts.TOKEN)).collect(Collectors.toList());
                authorization = list.size() > 0 ? list.get(0).getValue() : "";
            }
        }
        return authorization;
    }

}
